const SM4 = require('sm-crypto').sm4
const crypto = require('crypto-js')
// 加密
function encrypt_sm4(data, sm4Key, mode = 'CBC') {
  return SM4.encrypt(data, sm4Key, mode)
}

function descrypt_sm4(data, sm4Key, mode = 'CBC') {
  return SM4.decrypt(data, sm4Key, mode)
}
// 解密多个字段
function descrypt_fields_sm4(obj, sm4Key, fields = []) {
  fields.forEach((field) => {
    if (obj[field]) obj[field] = descrypt_sm4(obj[field], sm4Key)
  })
  return obj
}

function md5(data) {
  return crypto.MD5(data).toString(crypto.enc.Hex)
}

/**
 * 密码加密
 * @param {*} plainTxt 明文
 * @param {*} salt 盐
 * @returns
 */
function passwd_encrypt_md5(plainTxt, salt) {
  return md5(`${salt}_${plainTxt.trim()}_${salt}`)
}

function passwd_encrypt_sm4(plainTxt, sm4Key) {
  return encrypt_sm4(plainTxt, sm4Key)
}

function passwd_decrypt_sm4(encryptedTxt, sm4Key) {
  return descrypt_sm4(encryptedTxt, sm4Key)
}

module.exports = {
  encrypt_sm4,
  descrypt_sm4,
  md5,
  passwd_encrypt_md5,
  passwd_encrypt_sm4,
  passwd_decrypt_sm4,
  descrypt_fields_sm4,
}
